<script setup>
import { ref } from 'vue'
import axios from "@/utils/request.js";
import { matchSelectService, } from '@/api/match';
import { userPageService } from "@/api/user.js";
import { teacherSelectService } from "@/api/teacher.js";
import { awardAddService, awardSelectService,awardDeleteService,awardModifyService,awardExportService } from "@/api/award.js";
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted } from "vue";

import { fileUploadService } from '@/api/file';
import { MdPreview } from 'md-editor-v3';
// import { MDEditor } from 'md-editor-v3';
// import {MdEditor} from 'md-editor-v3';
import 'md-editor-v3/lib/preview.css';
import moment from 'moment';
// 分页查询
const awardInfo = ref([])
const selectIds = Array


const handleSelectionChange = (selection) => {
  selectIds.value = selection.map(item => item.awardId)
}

//分页查询底部导航栏
const pageNo = ref(1)
const pageSize = ref(10)
const awardNameInput = ref()
const groupNameInput = ref()
const total = ref(0)

//页面加载的时候发送一次查询请求
onMounted(() => {
  load()
})
const handleCurrentChange = (val) => {
  pageNo.value = val
  load()
}
const handleSizeChange = (val) => {
  pageSize.value = val
  load()
}
const matchNameFuzzy = ref()
const userNameFuzzy = ref()
const teacherNameFuzzy = ref()
//发送分页查询请求（包括搜索功能）
const load = async () => {
  const res = await awardSelectService(
    pageNo.value, pageSize.value, matchNameFuzzy.value, userNameFuzzy.value, teacherNameFuzzy.value
  )
  if (res.data.status === 'success') {
    awardInfo.value = res.data.data.list
    total.value = res.data.data.totalCount
  } else {
    ElMessage.error(res.data.info)
  }
}

/**
 * 添加获奖信息
 */
//定义模态窗口变量和表格对象
const introduceModel = ref(false)
const showAddModal = ref(false)
const awardInfoAddForm = ref({
  awardId: '',
  matchInfo: {
    matchId: '',
    matchName: ''
  },
  userInfo: {
    userId: '',
    userName: ''
  },
  matchResult: '',
  teacherInfo: {
    teacherId: '',
    teacherName: ''
  }
})
//  根据条件获取所有比赛信息
const matchList = ref([])
const currentMatchName = ref()
const matchLoading = ref(false)
const handleInputMatchChange = (query) => {
  matchLoading.value = true;
  setTimeout(() => {
    loadMatch(query)
    matchLoading.value = false;
  }, 1000);
}
const loadMatch = async (name) => {
  const res = await matchSelectService(1, 100000, name, '')
  matchList.value = res.data.data.list
}
const changeMatch = (matchInfo) => {
  if (!matchInfo) return
  awardInfoAddForm.value.matchInfo = matchInfo
}
//修改
const changeModifyMatch = (matchInfo) => {
  if (!matchInfo) return
  awardForm.value.matchInfo = matchInfo
}
//  根据条件获取所有队员信息
const userList = ref([])
const currentUserName = ref()
const userLoading = ref(false)
const handleInputUserChange = (query) => {
  userLoading.value = true;
  setTimeout(() => {
    loadUser(query)
    userLoading.value = false;
  }, 1000);
}
const loadUser = async (name) => {
  const res = await userPageService(1, 100000, '', name, '')
  userList.value = res.data.data.list
}
const changeUser = (userInfo) => {
  if (!userInfo) return
  awardInfoAddForm.value.userInfo.userId = userInfo.userId
  awardInfoAddForm.value.userInfo.userName = userInfo.name
}
const changeModifyUser = (userInfo) => {
  if (!userInfo) return
  awardForm.value.userInfo.userId = userInfo.userId
  awardForm.value.userInfo.userName = userInfo.name
}
//  根据条件获取所有老师信息
const teacherList = ref([])
const currentTeacherName = ref()
const teacherLoading = ref(false)
const handleInputTeacherChange = (query) => {
  teacherLoading.value = true;
  setTimeout(() => {
    loadTeacher(query)
    teacherLoading.value = false;
  }, 1000);
}
const loadTeacher = async (name) => {
  const res = await teacherSelectService(1, 100000, name)
  teacherList.value = res.data.data.list
}
const changeTeacher = (teacherInfo) => {
  if (!teacherInfo) return
  awardInfoAddForm.value.teacherInfo = teacherInfo
}
const changeModifyTeacher = (teacherInfo) => {
  if (!teacherInfo) return
  awardForm.value.teacherInfo = teacherInfo
}
//打开模态窗口
const openAddModal = () => {
  //清空对象内容
  awardInfoAddForm.value = {
    matchInfo: {
      matchId: '',
      matchName: ''
    },
    userInfo: {
      userId: '',
      userName: ''
    },
    matchResult: '',
    teacherInfo: {
      teacherId: '',
      teacherName: ''
    }
  }
  showAddModal.value = true
}
//定义校验规则变量
const ruleFormRef = ref()
const ruleFormModifyRef = ref()
const rules = {
  'matchInfo.matchName': [
    { required: true, message: '比赛名称不能为空', trigger: 'change' },
  ],
  matchResult: [
    { required: true, message: '获奖级别不能为空', trigger: 'change' },
  ],
  'userInfo.userName': [
    { required: true, message: '队员姓名不能为空', trigger: 'change' },
  ],
  'teacherInfo.teacherName': [
    { required: true, message: '指导老师不能为空', trigger: 'change' },
  ],
}
//发送添加获奖请求
const addAwardInfo = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      // 解构 awardInfoAddForm.value 中的嵌套属性
      const {
        matchInfo: { matchId, matchName },
        userInfo: { userId, name },
        matchResult,
        teacherInfo: { teacherId, teacherName }
      } = awardInfoAddForm.value;
      awardInfoAddForm.value.matchId = matchId
      awardInfoAddForm.value.matchName = matchName
      awardInfoAddForm.value.userId = userId
      awardInfoAddForm.value.userName = name
      awardInfoAddForm.value.teacherId = teacherId
      awardInfoAddForm.value.teacherName = teacherName
      const res = await awardAddService(awardInfoAddForm.value)
      if (res.data.status === 'success') {
        await load()
        ElMessage.success('添加成功')
        showAddModal.value = false
      } else {
        ElMessage.error(res.data.info)
      }
    }
  })
}

/**
 * 修改获奖信息
 * @type {Ref<UnwrapRef<boolean>, UnwrapRef<boolean> | boolean>}
 */
//修改获奖（弹出模态窗口）
//定义模态窗口变量和表格对象
const modifyIntroduceModel = ref(false)
const showModifyModal = ref(false)
const awardForm = ref({
    awardId: '',
    matchInfo: {
      matchId: '',
      matchName: ''
    },
    userInfo: {
      userId: '',
      userName: ''
    },
    matchResult: '',
    teacherInfo: {
      teacherId: '',
      teacherName: ''
    }
  })
const openModifyModal = (awardInfo) => {
  //将获奖数据渲染到模态窗口的表格上面
  awardForm.value.awardId = awardInfo.awardId
  awardForm.value.matchInfo.matchId = awardInfo.matchId
  awardForm.value.matchInfo.matchName = awardInfo.matchName
  awardForm.value.userInfo.userId = awardInfo.userId
  awardForm.value.userInfo.userName = awardInfo.userName
  awardForm.value.matchResult = awardInfo.matchResult
  awardForm.value.teacherInfo.teacherId = awardInfo.teacherId
  awardForm.value.teacherInfo.teacherName = awardInfo.teacherName
  //打开模态窗口
  showModifyModal.value = true
}

//发送修改获奖请求
const handleEdit = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      // 解构 awardForm.value 中的嵌套属性
      const {
        matchInfo: { matchId, matchName },
        userInfo: { userId, userName },
        matchResult,
        teacherInfo: { teacherId, teacherName }
      } = awardForm.value;
      awardForm.value.matchId = matchId
      awardForm.value.matchName = matchName
      awardForm.value.userId = userId
      awardForm.value.userName = userName
      awardForm.value.teacherId = teacherId
      awardForm.value.teacherName = teacherName
      const res = await awardModifyService(awardForm.value)
      if (res.data.status === 'success') {
        await load()
        ElMessage.success('修改成功')
        showModifyModal.value = false
      } else {
        ElMessage.error(res.data.info)
      }
    }
  })
}

/**
 * 删除获奖
 */
const openDeleteModal = (awardId) => {
  ElMessageBox.confirm(
    '确定要删除该获奖吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const awardIds = Array.of(awardId)
      const res = await awardDeleteService(awardIds)
      if (res.data.status === 'success') {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      } else {
        ElMessage({
          type: 'error',
          message: '删除失败',
        })
      }
      await load()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
/**
 * 批量删除获奖
 */
const openDeleteAllModal = () => {
  //非空判断
  if (selectIds.value == null) {
    ElMessage.info('未选中任何一条获奖信息')
    return
  }
  if (selectIds.value != null && selectIds.value.length === 0) {
    ElMessage.info('未选中任何一条获奖信息')
    return
  }
  //批量删除
  ElMessageBox.confirm(
    '确定要删除所有选中的获奖信息吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await awardDeleteService(selectIds.value)
      if (res.data.status === 'success') {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      } else {
        ElMessage({
          type: 'error',
          message: '删除失败',
        })
      }
      load()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

/**
 * 导出excel表格
 */
 const exportExcel = async() => {
  const res = await awardExportService(pageNo.value,pageSize.value,currentMatchName.value,currentUserName.value,currentTeacherName.value)
  if(res.status === 200){
     // 创建Blob对象
     const file = new Blob([res.data], { type: res.data.type });
    // 创建URL对象
    const fileURL = URL.createObjectURL(file);
    // 创建一个隐藏的a标签并设置属性
    const link = document.createElement('a');
    link.href = fileURL;
    link.setAttribute('download', 'award_info.xlsx'); // 设置下载文件名
    document.body.appendChild(link);
    link.click(); // 触发下载
    document.body.removeChild(link); // 清理DOM
    URL.revokeObjectURL(fileURL); // 释放URL对象
    await ElMessage.success('导出成功')
  }else{
    ElMessage.error('导出失败')
  }
}

/**
 * 导入excel表格
 */
const handleImport = (res,file,fileList) => {
  if(!file.name.toLowerCase().endsWith('.xlsx')){
    ElMessage.error('请上传.xlsx类型的文件')
    return
  }
  if(res.status === 'success'){
    load()
    ElMessage.success('导入成功')
  }else{
    ElMessage.error(res.info)
  }
}

const getToken = () => {
  return localStorage.getItem('token')
}
</script>

<template>
  <!--  模态窗口-->
  <!--  修改成员信息模态窗口-->
  <div class="modify-modal" v-show="showModifyModal">
    <div class="modify-form">
      <div class="close-btn" @click="showModifyModal = false">&times;</div>
      <h1 style="text-align: center;font-size: 30px">修改获奖信息</h1>
      <el-form :model="awardForm" ref="ruleFormModifyRef" :rules="rules" label-width="auto"
        style="max-width: 600px;margin: auto;margin-top: 50px">
        <el-form-item label="比赛名称" prop="matchInfo.matchName">
          <el-select v-model="awardForm.matchInfo.matchName" clearable placeholder="请查找并选择比赛名称" style="width: 240px" filterable
            :remote="true" :remote-method="handleInputMatchChange" @change="changeModifyMatch" :loading="matchLoading">
            <el-option v-for="(item, index) in matchList" :key="index" :label="item.matchName" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="获奖级别" prop="matchResult">
          <el-radio-group v-model="awardForm.matchResult">
            <el-radio :value="1">一等奖</el-radio>
            <el-radio :value="2">二等奖</el-radio>
            <el-radio :value="3">三等奖</el-radio>
            <el-radio :value="4">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属队员" prop="userInfo.userName" :label-width="80">
          <el-select v-model="awardForm.userInfo.userName" clearable placeholder="请查找并选择所属队员" style="width: 240px" filterable
            :remote="true" :remote-method="handleInputUserChange" @change="changeModifyUser" :loading="userLoading">
            <el-option v-for="(item, index) in userList" :key="index" :label="item.name" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="指导老师" prop="teacherInfo.teacherName" :label-width="80">
          <el-select v-model="awardForm.teacherInfo.teacherName" clearable placeholder="请查找并选择指导老师" style="width: 240px" filterable
            :remote="true" :remote-method="handleInputTeacherChange" @change="changeModifyTeacher" :loading="teacherLoading">
            <el-option v-for="(item, index) in teacherList" :key="index" :label="item.teacherName" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="handleEdit(ruleFormModifyRef)">修改</el-button>
          <el-button @click="showModifyModal = false">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
  <!--  添加获奖模态窗口-->
  <div class="modify-modal" v-show="showAddModal">
    <div class="modify-form">
      <div class="close-btn" @click="showAddModal = false">&times;</div>
      <h1 style="text-align: center;font-size: 30px">添加获奖信息</h1>
      <el-form :model="awardInfoAddForm" ref="ruleFormRef" :rules="rules" label-width="auto"
        style="max-width: 600px;margin: auto;margin-top: 50px">
        <el-form-item label="比赛名称" prop="matchInfo.matchName">
          <el-select v-model="awardInfoAddForm.matchInfo.matchName" clearable placeholder="请查找并选择比赛名称" style="width: 240px" filterable
            :remote="true" :remote-method="handleInputMatchChange" @change="changeMatch" :loading="matchLoading">
            <el-option v-for="(item, index) in matchList" :key="index" :label="item.matchName" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="获奖级别" prop="matchResult">
          <el-radio-group v-model="awardInfoAddForm.matchResult">
            <el-radio :value="1">一等奖</el-radio>
            <el-radio :value="2">二等奖</el-radio>
            <el-radio :value="3">三等奖</el-radio>
            <el-radio :value="4">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属队员" prop="userInfo.userName" :label-width="80">
          <el-select v-model="awardInfoAddForm.userInfo.userName" clearable placeholder="请查找并选择所属队员" style="width: 240px" filterable
            :remote="true" :remote-method="handleInputUserChange" @change="changeUser" :loading="userLoading">
            <el-option v-for="(item, index) in userList" :key="index" :label="item.name" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="指导老师" prop="teacherInfo.teacherName" :label-width="80">
          <el-select v-model="awardInfoAddForm.teacherInfo.teacherName" clearable placeholder="请查找并选择指导老师" style="width: 240px" filterable
            :remote="true" :remote-method="handleInputTeacherChange" @change="changeTeacher" :loading="teacherLoading">
            <el-option v-for="(item, index) in teacherList" :key="index" :label="item.teacherName" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="addAwardInfo(ruleFormRef)">添加</el-button>
          <el-button @click="showAddModal = false">取消</el-button>
        </el-form-item>
      </el-form>

    </div>

  </div>


  <div>
    <!--    功能按钮-->
    <el-card style="width: 36%;margin-bottom: 30px;float: left">
      <el-button @click="openAddModal" type="primary">添加获奖</el-button>
      <el-button @click="openDeleteAllModal" type="danger">批量删除</el-button>
      <el-button @click="exportExcel" type="success">导出Excel</el-button>
      <el-upload style="display: inline-block;margin-left: 12px"
                 :show-file-list="false"
                 :on-success="handleImport"
                 accept=".xlsx,.xls"
                 :headers="{token: getToken()}"
      :action="axios.defaults.baseURL + '/awardResult/uploadExcel'">
        <el-button type="success">导入Excel</el-button>
      </el-upload>
    </el-card>
    <!--    搜索框-->
    <el-card class="member-search">
      <span style="margin-left: 10px">
        <h1>比赛名称：</h1>
      </span>
      <input v-model="matchNameFuzzy" @keyup.enter.native="load">
      <span style="margin-left: 10px">
        <h1>队员姓名：</h1>
      </span>
      <input v-model="userNameFuzzy" @keyup.enter.native="load">
      <span style="margin-left: 10px">
        <h1>老师姓名：</h1>
      </span>
      <input v-model="teacherNameFuzzy" @keyup.enter.native="load" style="border-right: none;">
      <el-button type="warning" @click="load">搜索</el-button>
    </el-card>
  </div>
  <div>
    <el-table ref="multipleTableRef" :data="awardInfo" stripe style="width: 100%;margin-top: 30px"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column property="matchName" label="比赛名称" width="170" />
      <el-table-column property="userName" label="队员姓名" width="170">
      </el-table-column>
      <el-table-column property="matchResult" label="获奖级别" width="170">
        <template #default="scope">
          <div v-if="scope.row.matchResult === 1">一等奖</div>
          <div v-if="scope.row.matchResult === 2">二等奖</div>
          <div v-if="scope.row.matchResult === 3">三等奖</div>
          <div v-if="scope.row.matchResult === 4">其他</div>
        </template>
      </el-table-column>
      <el-table-column property="teacherName" label="指导老师" width="170" />
      <el-table-column property="updateTime" label="修改时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" type="info" @click="openModifyModal(scope.row)">
            修改
          </el-button>
          <el-button size="small" type="danger" @click="openDeleteModal(scope.row.awardId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页组件-->
    <el-card style="margin-top: 20px;float: right;">
      <div class="demo-pagination-block">
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[2, 5, 10, 20]"
          size="large" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @current-change="handleCurrentChange" @size-change="handleSizeChange" />
      </div>
    </el-card>

  </div>
</template>


<style scoped>
/*模态窗口样式*/
.modify-modal {
  position: fixed;
  z-index: 10;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: black;
  opacity: 1;
}

/*模态窗口表格样式*/
.modify-form {
  background-color: #ffffff;
  margin: 5% auto;
  /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  z-index: 10;
  border-radius: 10%;
  width: 30%;
  /* Could be more or less, depending on screen size */
}

.close-btn {
  cursor: pointer;
  color: #000000;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

/*搜索样式*/
.member-search {
  width: 61%;
  float: right
}

.member-search span {
  float: left;
}

.member-search input {
  float: left;
  height: 20px;
  width: 15%;
  border: solid 2px;
  margin-top: 2px;
}

/*表头样式*/
:deep() th.el-table__cell {
  color: black;
  font-size: 15px;
}
</style>
